package com.suning.framework;

import com.suning.framework.utils.EsUtils;
import net.sf.json.JSONObject;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;

import java.util.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author 16080951(林健)
 * @Copyright (c) 2016 苏宁软件技术有限公司 版权所有
 * @see [相关类/方法]（可选）
 * @since [产品 /模块版本] （可选）
 */
public class TestCity {

    private final static String IP = "127.0.0.1";

    private final static int PORT = 9300;

    //索引
    private final static String INDEX = "suning";

    //类型
    private final static String TYPE = "portait";

    private static TestCity test = new TestCity();

    /**
     * 存es
     * XPOST 'localhost:9200/xxx/_bulk?pretty' -d '{}'
     */
    public void setInfo(){

        List<CityInfo> cityInfoList = new ArrayList<CityInfo>();
        List<Company> companyList = new ArrayList<Company>();
        for(int i = 0;i<2;i++) {
            CityInfo cityInfo = new CityInfo();
            cityInfo.setCityCode("225" + i);
            cityInfo.setCityName("测试地市225"+i);
            cityInfoList.add(cityInfo);
        }

        Client client = EsUtils.openConnection();
        BulkRequestBuilder bulkRequest = client.prepareBulk();
        for (CityInfo cityInfo : cityInfoList) {
            bulkRequest.add(
                    client.prepareIndex(INDEX,"city", cityInfo.getCityCode()).setSource(JSONObject.fromObject(cityInfo).toString())
            );
        }

        //添加数据到company里
        for(int i = 0;i<2;i++) {
            Company company = new Company();
            company.setCompanyName("公司名字"+i);
            company.setCompanyCode("公司编号"+i);
            companyList.add(company);
        }

        for (int i = 0;i < companyList.size();i++) {
            Company company = companyList.get(i);
            CityInfo cityInfo = cityInfoList.get(i);
            bulkRequest.add(
                    client.prepareIndex(INDEX,"company",company.getCompanyCode() ).setParent(cityInfo.getCityCode()).setSource(JSONObject.fromObject(company).toString())
            );
        }


        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        if (bulkResponse.hasFailures()) {
            //处理错误
            System.out.println("处理错误！！！");
        }

        client.close();

    }

    /**
     * 添加数据到ES
     */
    private static void doAdd() {

        //放入es
        test.setInfo();
    }

    /**
     * 删除
     */

    public void deletes(){
        Client client = EsUtils.openConnection();
        client.prepareDelete().setIndex("").setType("").execute().actionGet();
    }

    /**
     * 分页查询
     *
     * @return the list
     */
    public static List<Mps_member_portrait_info> doPageQuery(){
        Client client = EsUtils.openConnection();

        //每页多少条
        long pageSize = 100;

        //匹配查询,配合.setQuery(queryBuilder)
        //QueryBuilder queryBuilder = new MatchQueryBuilder("acct_no","0000000000033171278");
        //QueryBuilder queryBuilderMap = new HasParentQueryBuilder("acct_no","0000000000033171278");
        //QueryBuilder queryBuilderMap = new HasChildQueryBuilder("acct_no","0000000000033171278");


        SearchResponse searchResponse =
                client.prepareSearch(INDEX)
                        .setTypes("city")
                        .setSearchType(SearchType.DFS_QUERY_AND_FETCH)
                        //.setQuery(queryBuilder)
                        .setScroll(TimeValue.timeValueMinutes(1))
                        .setSize((int)pageSize / 5) //返回条数 = 分片数 * size
                        .execute()
                        .actionGet();


        //总量
        long total = searchResponse.getHits().getTotalHits();
        System.out.println("total : " + total);

        //共多少页
        long totalPage = ( total % pageSize == 0 ) ? total / pageSize : (total / pageSize)+1;

        //当前页
        long currentPage = 1;
        List<SearchHit> result = new ArrayList<SearchHit>();
        while (true) {
            searchResponse = client.prepareSearchScroll(searchResponse.getScrollId())
                    .setScroll(TimeValue.timeValueMinutes(1))
                    .execute()
                    .actionGet();

            if(searchResponse.getHits().hits().length == 0)break;
            else{
                //将所有数据放入List
                Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
                while(iterator.hasNext()){
                    SearchHit hit = iterator.next();
                    result.add(hit);
                }

                if(result.size() > 10000) break;
            }
        }

        //当前result中的总数据量
        System.out.println(result.size());

        //分页取数据
        for(int i = 0 ; i < totalPage && currentPage <= totalPage ;i++ ){

            List _tmp = result.subList((int)((currentPage - 1)*pageSize),(int)((currentPage * pageSize > total ? total : currentPage * pageSize)));
            currentPage++;

        }

        for(SearchHit obj : result){
            String json = obj.getSourceAsString();
            System.out.println(json);
        }
        client.close();
        return null;
    }


    /**
     * 分页查询
     *
     * @return the list
     */
    public static void doMatchQuery(){
        Client client = EsUtils.openConnection();

        QueryBuilder queryBuilder = new MatchAllQueryBuilder();

        SearchResponse searchResponse =
                client.prepareSearch(INDEX)
                        .setTypes("city")
                        .setSearchType(SearchType.DFS_QUERY_AND_FETCH)
                        .setQuery(queryBuilder)
                        .setTimeout(TimeValue.timeValueMinutes(1))
                        .execute()
                        .actionGet();

        //总量
        long total = searchResponse.getHits().getTotalHits();
        System.out.println("total : " + total);

        //将所有数据放入List
        Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while(iterator.hasNext()){
            SearchHit hit = iterator.next();
            String json = hit.getSourceAsString();
            System.out.println(json);
        }

        client.close();
    }

    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {

        //添加数据到ES
        //doAdd();

        //模拟分页数据查询
        //doPageQuery();

        //模拟匹配查询
        //doMatchQuery();

    }

}
